<template>
  <el-dialog title="批量导入" class="import-dialog" :width="width" :top="top" :visible="visible" @close="close('close-icon')">
    <el-steps finish-status="success" :active="active" align-center>
      <el-step title="上传文件" />
      <el-step title="执行导入" />
      <el-step title="导入完成" />
    </el-steps>
    <section v-show="active===0">
      <div class="im-block">
        <p class="icon"><i class="el-icon-document" /></p>
        <div class="desc">
          <p class="title">{{ descInfo[0] }}</p>
          <p class="title-desc">请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除</p>
          <div class="control-box">
            <elink-loading class="control" name="下载模板" @clickDown="downloadTemplate" />
            <!-- <upload-files ref="uploadFiles" class="control" @onSuccess="setFile" /> -->
          </div>
        </div>
      </div>
      <div class="im-block">
        <p class="icon"><i class="el-icon-upload2" /></p>
        <div class="desc">
          <p class="title">{{ descInfo[1] }}</p>
          <p class="title-desc">文件后缀名必须为xls 或xlsx （即Excel格式），文件大小不得大于{{ fileSize }}M</p>
          <div class="control-box">
            <upload-files ref="uploadFiles" class="control" :file-size="fileSize" @onSuccess="setFile" />
          </div>
        </div>
      </div>
      <slot name="tips" />
      <div class="dialog-footer">
        <el-button v-debounce="judgeImport" type="primary" class="btn">下一步</el-button>
      </div>
    </section>
    <section v-show="active===1">
      <div class="im-block">
        <p class="icon"><i class="el-icon-document-checked" /></p>
        <div class="desc">
          <p class="title">{{ descInfo[2] }}</p>
          <div class="control-box">
            <el-link type="primary" :underline="false" class="control">{{ judgmentResult.correctNum }}{{ descInfo[7] }}</el-link>
          </div>
        </div>
      </div>
      <div class="im-block">
        <p class="icon"><i class="el-icon-document-delete" /></p>
        <div class="desc">
          <p class="title">{{ descInfo[3] }}</p>
          <div class="control-box">
            <el-link type="primary" :underline="false" class="control">{{ judgmentResult.errorNum }}{{ descInfo[7] }}</el-link>
          </div>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button v-debounce="()=>{isImport(1)}" type="primary" :icon="isImportBtn===1?`el-icon-loading`:``" :disabled="isOk" class="btn">确认导入</el-button>
        <el-button v-debounce="()=>{isImport(0)}" :icon="isImportBtn===0?`el-icon-loading`:``" :disabled="judgeImportComplete" class="btn">返回重新上传</el-button>
      </div>
      <section v-if="judgmentResult.dataList&&judgmentResult.dataList.length" class="table-area">
        <span class="desc">{{ descInfo[4] }}</span>
        <elink-loading v-if="downloadErrorDataShow" class="control" name="下载错误数据" @clickDown="downloadErrorData" />
        <table-pagination class="error-table" :pagination-show="paginationShow" :layout="'total, prev, pager, next'" :columns="errorColumns" :data="judgmentResult.dataList" :current-page="currentPage" :total="total" border @handlePaginationChange="handlePaginationChange" />
      </section>
    </section>
    <section v-show="active===2" class="complete">
      <i class="el-icon-success" />
      <p>批量导入完成</p>
      <span class="title-desc">{{ descInfo[5] }}:{{ totalCorrectNum }}{{ descInfo[6] }}</span>
      <div class="dialog-footer">
        <el-button class="btn" type="primary" @click="close">完 成</el-button>
      </div>
    </section>
    <section v-show="active===1&&progressSection" class="progress">
      <div class="progress-box">
        <el-progress v-show="progressShow" type="circle" :percentage="uploadPercentage" :stroke-width="16" :format="uploadProgressFormat" :width="200" />
        <el-progress v-show="progressAxios" type="circle" :percentage="percentage" :stroke-width="16" :format="format" :width="200" />
      </div>
    </section>
  </el-dialog>
</template>
<script>

import UploadFiles from '@/components/common/UploadFiles';
import TablePagination from '@/components/common/TablePagination';
import ElinkLoading from './elinkLoading.vue';
import config from './config';
export default {
  name: 'ImportFile',
  components: {
    UploadFiles,
    TablePagination,
    ElinkLoading
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    fileSize: {
      type: Number,
      default: 2
    },
    descInfo: {
      type: Object,
      default: () => ({
        0: '填写导入商品的信息',
        1: '上传填好的商品信息表',
        2: '本次导入商品条数',
        3: '本次不可导入商品条数',
        4: '不可导入商品明细',
        5: '成功导入商品数量',
        6: '条',
        7: '个'
      })
    },
    errorColumns: {
      type: Array,
      default: () => { return config.errorColumns; }
    },
    downloadErrorDataShow: {
      type: Boolean,
      default: true
    },
    paginationShow: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: '1000px'
    },
    top: {
      type: String,
      default: '50px'
    }
  },
  data() {
    return {
      active: 0,
      judgmentResult: {
        correctNum: '-',
        errorNum: '-',
        dataList: []
      },
      percentage: 0,
      uploadPercentage: 0,
      progressShow: false,
      progressAxios: false,
      progressSection: false,
      file: '',
      isImportBtn: null,
      judgeImportComplete: false,
      isOk: true, // 导入是否正常
      totalCorrectNum: '-',
      currentPage: 1,
      total: 0
    };
  },
  watch: {
    progressAxios(val) {
      if (val) {
        const timer = setInterval(() => {
          if (this.percentage < 99) {
            this.percentage += 1;
          } else {
            clearInterval(timer);
          }
        }, 100);
      }
    }
  },
  methods: {
    // 上传文件设置文件
    setFile(fileList) {
      this.file = fileList[0];
    },
    // 上传进度格式化
    uploadProgressFormat(percentage) {
      if (percentage === 100) {
        setTimeout(() => {
          this.progressShow = false;
          this.uploadPercentage = 0;
          this.progressAxios = true;
        }, 300);
      }
      return `${percentage}%`;
    },
    format(percentage) {
      return `上传完毕,解析中${percentage}%`;
    },
    // 错误数据列表展示分页事件
    handlePaginationChange({ current, size }) {
      this.$emit('getErrorPage', { current, size });
    },
    // 设置错误数据列表数据
    setErrorTableData(current, data) {
      this.currentPage = current;
      this.judgmentResult.dataList = data;
    },
    // 执行导入逻辑判断
    judgeImport() {
      if (!this.file) {
        this.$message.warning('请导入文件！');
        return;
      }
      this.active = 1;
      this.uploadPercentage = 0;
      this.percentage = 0;
      this.progressAxios = false;
      this.progressSection = true;
      this.progressShow = true;
      const formData = new FormData();
      formData.append('file', this.file.raw);
      this.$emit('firstImport', formData);
    },
    // 重置请求进度条
    resetProgress() {
      this.percentage = 100;
      setTimeout(() => {
        this.progressSection = false;
        this.progressShow = false;
        this.progressAxios = false;
      }, 1000);
    },
    // 导入进入第二步骤
    toSecond(data) {
      this.isOk = false;
      this.judgmentResult.errorNum = data.errorNum;
      this.judgmentResult.correctNum = data.correctNum;
      this.total = this.judgmentResult.errorNum;
      this.percentage = 100;
      setTimeout(() => {
        this.progressSection = false;
        this.progressAxios = false;
      }, 1000);
    },
    // 确认导入进入第三步骤
    toThird(totalCorrectNum) {
      this.totalCorrectNum = totalCorrectNum;
      this.active = 2;
      this.$emit('complete');
    },
    // 确认导入或返回重新上传
    isImport(proceed) {
      this.judgeImportComplete = true;
      this.isOk = true;
      this.isImportBtn = proceed;
      this.$emit('isImport', proceed);
    },
    // 重置按钮状态
    resetStatus() {
      this.isImportBtn = null;
      this.judgeImportComplete = false;
      this.isOk = true;
    },
    // 上传文件xhr进度
    onUploadProgress(progressEvent) {
      // progressEvent.loaded:已上传文件大小
      // progressEvent.total:被上传文件的总大小
      this.uploadPercentage = (progressEvent.loaded / progressEvent.total * 100);
    },
    // 完成关闭弹窗
    close(type) {
      if (type === 'close-icon' && this.judgeImportComplete) {
        const info = this.isImportBtn ? '文件导入中，请稍后' : '撤销操作中，请稍后';
        this.$message.info(info);
        return;
      }
      this.$emit('close');
      this.resetData();
    },
    // 重置数据 回到第一步骤
    resetData() {
      this.$nextTick(() => {
        this.active = 0;
        this.judgmentResult = {
          correctNum: '-',
          errorNum: '-',
          dataList: []
        };
        this.$refs.uploadFiles.delFile();
        this.totalCorrectNum = '-';
      });
    },
    // 下载模板
    downloadTemplate() {
      this.$emit('downLoadTemplateFile');
    },
    // 下载错误数据
    downloadErrorData() {
      this.$emit('downLoadErrorFileData');
    }
  }
};
</script>

<style lang="scss" scoped>
.import-dialog{
  .title-desc{
    font-size: 12px;
    color: #999;
  }
  .btn{
    padding: 8px 30px;
  }
  .tips{
    display: flex;
    justify-content: space-between;
    padding: 10px 0 30px;
  }
  .progress{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: self-start;
    .progress-box{
      height: 542px;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .im-block{
    width: 100%;
    height: 100px;
    display: flex;
    border: 1px solid #eee;
    align-items: center;
    margin: 20px 0;
    .icon{
      width: 80px;
      background-color: #eee;
      margin: 0;
      height: 100px;
      margin-right: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
    }
    .title,.title-desc,.control{
      margin-bottom: 4px;
    }
    .control-box{
      display: flex;
      align-items: center;
    }
    .control{
      font-size: 12px;
      padding-right: 10px;
    }
  }
  .dialog-footer{
    text-align: center;
  }
  .table-area{
    margin: 20px 0;
    .desc{
      font-size: 12px;
      padding-right: 10px;
    }
    .error-table{
    margin-top: 10px;
    }
  }
  .complete{
    margin-top: 10px;
    text-align: center;
    .el-icon-success{
      font-size: 100px;
      color: #67c23a;
    }
    .dialog-footer{
      margin-top: 20px;
    }
    p{
      margin: 0;
      font-size: 20px;
    }
  }
}
::v-deep {
  .el-steps--horizontal{
    position: relative;
    left: -18%;
    width: 136%;
  }
  .el-step__title.is-success {
    font-weight: 700;
    color: #303133;
  }
  .el-step__head.is-success {
    color: #409eff;
    border-color: #409eff;
  }
  .el-step__title{
    font-size: 14px;
  }
  .el-upload-list__item:first-child {
    margin-top: 0;
  }
  .el-step__head.is-process {
    color: #409eff;
    border-color: #409eff;
  }
  .el-progress--circle .el-progress__text, .el-progress--dashboard .el-progress__text{
    font-size: 16px!important;
  }
}
</style>
